package com.steven.concurrency.example.atomic;


import com.steven.concurrency.annoations.ThreadSafe;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@ThreadSafe
public class AtomicTest_Boolean {


    //请求总数
    private static int clientTotal=5000;
    //并发数量
    private static int threadTotal=200;

    public static AtomicInteger count =new AtomicInteger(0);

    public static AtomicBoolean booleans = new AtomicBoolean(false);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i <clientTotal ; i++) {
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(
                booleans
        );
    }


    public static void  add(){
        //只执行一次
        if(booleans.compareAndSet(false,true)){
            System.out.println("excute");
        }

    }
    /**
     * atomicStampReference 解决CAS ABA问题 :给数据加版本，每次操作的时候比较版本号
     */
}


